<?php
/**
 * Created by PhpStorm.
 * User: 87976
 * Date: 2018/1/29
 * Time: 10:15
 */

namespace App\Services\Album;


use App\Abstracts\TemplateAbstract;
use App\Repositories\Album\AlbumToAlbumRepository;
use Symfony\Component\Translation\Exception\NotFoundResourceException;

/**
 * Class AlbumToAlbumService
 * @package App\Services\Album
 */
class AlbumToAlbumService extends TemplateAbstract
{

    /**
     * @var AlbumToAlbumRepository
     */
    protected $albumToAlbumRepository;

    /**
     * AlbumToAlbumService constructor.
     * @param AlbumToAlbumRepository $albumToAlbumRepository
     */
    public function __construct(AlbumToAlbumRepository $albumToAlbumRepository)
    {
        $this->albumToAlbumRepository = $albumToAlbumRepository;
    }

    /**
     * @author Jerry
     * @param array $data
     * @return array|mixed
     */
    public function handle(array $data)
    {

        $albums = $this->albumToAlbumRepository->findAlbumsByTemplateId($data['id']);

        if (empty($albums)) {
            return [];
        }

        $albums = array_map('get_object_vars', $albums);

        $albumsData = $this->getAlbumsGoodsImage($albums);

        $data['album_data'] = $albumsData;

        unset($data['album_id']);


        return $data;
    }

    /**
     * @author Jerry
     * @param array $albums
     * @return array
     */
    protected function getAlbumsGoodsImage(array $albums)
    {
        if (empty($albums)) {
            throw new NotFoundResourceException('空的专辑');
        }

        foreach ($albums as $key => $value) {

            $count = $this->albumToAlbumRepository->isTemplateByAlbumId($value['id']);

            if (empty($count)) {
                continue;
            }

            $images = $this->albumToAlbumRepository->findAlbumGoodsImageByAlbumId($value['id']);

            if (empty($images)) {
                continue;
            }

            $images = $this->checkGoodsImages($images);

            $albums[$key]['image_data'] = $images;
        }

        return $albums;
    }


    /**
     *
     * @author Jerry
     * @param array $images
     * @return array
     */
    protected function checkGoodsImages(array $images)
    {
        if (empty($images)) {
            throw new NotFoundResourceException('空的的图片数组');
        }

        $data = [];

        foreach ($images as $key => $value) {
            $imagePath = $value->original_img;

            if (empty($images)) {
                continue;
            }

            $imageUri = cdn_asset($imagePath);

            $data[] = $imageUri;
        }

        return $data;
    }
}